/*
 * CadastroAluno.java
 *
 * Created on 18 de Janeiro de 2010, 16:40
 */

package calpi.gui;

import calpi.Aluno;
import calpi.Connectors;
import calpi.Curso;
import calpi.Disciplina;
import calpi.database.AlunosConnector;
import calpi.util.Comparadores;
import java.text.Collator;
import javax.swing.JFrame;
import static javax.swing.JOptionPane.*;
import java.util.TreeMap;

/**
 *
 * @author  marcosa
 */
public class CadastroAluno extends JFrame {

    //private Principal parent;
    private Curso[] cursos;
    //Para o caso de edição
    private Aluno aluno = null;
    //Disciplinas que podem ser cursadas
    private TreeMap<String, Disciplina> aCurs = null;
    private TreeMap<String, Disciplina> curs = null;
    
    public CadastroAluno(Principal pai, Curso[] cursos, Disciplina[] disciplinas) {

        this(pai, null, cursos, disciplinas);
    }
    
    /** Creates new form CadastroAluno */
    public CadastroAluno(Principal pai, Aluno aluno, Curso[] cursos, Disciplina[] disciplinas) {

        //parent = pai;
        this.cursos = cursos;
        initComponents();
        this.cursos = cursos;
        this.aluno = aluno;
        for (Curso c : cursos) {

            comboCursos.addItem(c.getNome());
        }

        //Verifica as disciplinas cursadas pelo aluno e as que não foram
        //Ordena por ordem alfabética
        Comparadores.COLLATOR.setStrength(Collator.PRIMARY);
        aCurs = new TreeMap<String, Disciplina>(Comparadores.COLLATOR);
        curs = new TreeMap<String, Disciplina>(Comparadores.COLLATOR);

        for (Disciplina d : disciplinas) {

            if (aluno != null) {

                if (aluno.cursada(d)) {

                    curs.put(d.getDescricao(), d);
                    continue;
                }
            }

            aCurs.put(d.getDescricao(), d);
        }

        //Adiciona ao lists
        disciCurs.setListData(curs.keySet().toArray());
        discACurs.setListData(aCurs.keySet().toArray());
        
        //Preenche os dados para edição
        if (aluno != null) {

            nome.setText(aluno.getNome());
            matricula.setText(String.valueOf(aluno.getMatricula()));
            ender.setText(aluno.getEndereco());
            periodo.setText(String.valueOf(aluno.getPeriodo()));
            comboCursos.setSelectedItem(aluno.getCurso().getNome());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        nome = new javax.swing.JTextField();
        ender = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        matricula = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        periodo = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        comboCursos = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        disciCurs = new javax.swing.JList();
        cur2acur = new javax.swing.JButton();
        acur2curs = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        discACurs = new javax.swing.JList();
        confirmar = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("CalpI - Cadastro de Alunos");
        setLocationByPlatform(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Nome");

        jLabel2.setText("Endereço");

        jLabel3.setText("Matrícula");

        jLabel4.setText("Período");

        jLabel5.setText("Curso");

        jLabel6.setText("Disciplinas Cursadas");

        jLabel7.setText("Disciplinas a Cursar");

        disciCurs.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(disciCurs);

        cur2acur.setIcon(new javax.swing.ImageIcon(getClass().getResource("/right.png"))); // NOI18N
        cur2acur.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cur2acurActionPerformed(evt);
            }
        });

        acur2curs.setIcon(new javax.swing.ImageIcon(getClass().getResource("/left.png"))); // NOI18N
        acur2curs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acur2cursActionPerformed(evt);
            }
        });

        discACurs.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(discACurs);

        confirmar.setText("Confirmar");
        confirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarActionPerformed(evt);
            }
        });

        jButton4.setText("Cancelar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(ender, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(acur2curs)
                            .addComponent(cur2acur))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(matricula, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(49, 49, 49)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(periodo, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(27, 27, 27)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(comboCursos, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel7)
                                .addGap(38, 38, 38)))))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(452, Short.MAX_VALUE)
                .addComponent(confirmar)
                .addGap(18, 18, 18)
                .addComponent(jButton4)
                .addGap(57, 57, 57))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(ender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(matricula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(periodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(comboCursos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(75, 75, 75)
                        .addComponent(cur2acur)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(acur2curs)))
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmar)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

        tryClose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void cur2acurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cur2acurActionPerformed

        String selecCurs = (String) disciCurs.getSelectedValue();
        if (selecCurs == null) {

            return;
        }

        Disciplina detDisc = curs.remove(selecCurs);
        if (detDisc != null) {

            aCurs.put(selecCurs, detDisc);
        }
        
        disciCurs.setListData(curs.keySet().toArray());
        discACurs.setListData(aCurs.keySet().toArray());
    }//GEN-LAST:event_cur2acurActionPerformed

    private void acur2cursActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acur2cursActionPerformed

        String selecACurs = (String) discACurs.getSelectedValue();
        if (selecACurs == null) {

            return;
        }

        Disciplina detDisc = aCurs.remove(selecACurs);
        if (detDisc != null) {

            curs.put(selecACurs, detDisc);
        }
        
        disciCurs.setListData(curs.keySet().toArray());
        discACurs.setListData(aCurs.keySet().toArray());
    }//GEN-LAST:event_acur2cursActionPerformed

    private void confirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarActionPerformed

        boolean error = false; //Caso existe algum erro na entrada de informações
        int mat = 0;
        int per = 0;
        AlunosConnector ac = null;
        
        try {

            ac = (AlunosConnector) Connectors.getConnector(Connectors.ALUNOS);
            mat = Integer.parseInt(matricula.getText());
            if (mat <= 0) {

                throw new NumberFormatException("Matrícula menor que zero");
            }
            
            if (aluno == null) {
                
                //Procura a existência de alguma aluno com mesma matrícula caso seja
                //novo cadastro

                //procura no buffer de saída que é o mais atualizado
                ac.setIterableBuffer(AlunosConnector.BUFFER_OUT);
                for (Aluno al : ac) {

                    if (al.getMatricula() == mat) {

                        showMessageDialog(this, "Já existe um aluno cadastrado com "
                                + "essa matrícula.", "CalpI - Cadastro de Alunos",
                                ERROR_MESSAGE);
                        return;
                    }
                }
            }

        } catch (NumberFormatException nfe) {

            showMessageDialog(this, "Número de matrícula é inválido.",
                    "CalpI - Cadastro de Alunos", ERROR_MESSAGE);
            error = true;
        }

        try {

            per = Integer.parseInt(periodo.getText());
            if (per <= 0) {

                throw new NumberFormatException("Período negativo.");
            }
        } catch (NumberFormatException nfe) {

            showMessageDialog(this, "Digite um período válido.",
                    "CalpI - Cadastro de Alunos", ERROR_MESSAGE);
            error = true;
        }

        String nomeAluno = nome.getText();
        if (nomeAluno.equals("")) {

            showMessageDialog(this, "Digite um nome válido.",
                    "CalpI - Cadastro de Alunos", ERROR_MESSAGE);
            error = true;
        }

        String enderAluno = ender.getText();
        if (enderAluno.equals("")) {

            showMessageDialog(this, "Digite um endereço válido.",
                    "CalpI - Cadastro de Alunos", ERROR_MESSAGE);
            error = true;
        }

        //Evitar processamento desnecessário =}
        if (error) {

            return;
        }

        Curso curso = cursos[comboCursos.getSelectedIndex()];
        Disciplina[] disciplinas = new Disciplina[curs.size()];
        curs.values().toArray(disciplinas);

        //Deleta o cadastro anterior
        if (aluno != null) {

            ac.removeElementBufferOut(aluno);
        }

        if (disciplinas.length > 0) {

            ac.addElementBufferOut(new Aluno(nomeAluno, mat, enderAluno, curso,
                    per, disciplinas));
        } else {

            ac.addElementBufferOut(new Aluno(nomeAluno, mat, enderAluno, curso, per));
        }

        //Pede para a escrita do novos dados
        Connectors.askWrite(Connectors.ALUNOS);
        showMessageDialog(this, (aluno == null
                                 ? "Aluno cadastrado com sucesso."
                                 : "Aluno modificado com sucesso"),
                    "CalpI - Cadastro de Alunos", INFORMATION_MESSAGE);
        
        setVisible(false);
        dispose();
        new Principal().setVisible(true);
    }//GEN-LAST:event_confirmarActionPerformed

    private void tryClose() {

        if (showConfirmDialog(this, "Deseja mesmo cancelar a ação?",
                "CalpI - Cadastro de Alunos", YES_NO_OPTION) == NO_OPTION) {

            return;
        }

        setVisible(false);
        dispose();
        new Principal().setVisible(true);
    }

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        tryClose();
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acur2curs;
    private javax.swing.JComboBox comboCursos;
    private javax.swing.JButton confirmar;
    private javax.swing.JButton cur2acur;
    private javax.swing.JList discACurs;
    private javax.swing.JList disciCurs;
    private javax.swing.JTextField ender;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField matricula;
    private javax.swing.JTextField nome;
    private javax.swing.JTextField periodo;
    // End of variables declaration//GEN-END:variables

}
